package com.lyz.util;

import java.lang.reflect.Type;

import org.apache.log4j.Logger;


import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
/**
 * 
 * @author luyongzhao
 *
 */
public class GsonExt {
	
	private static final Logger logger = Logger.getLogger(GsonExt.class);
	private Gson gson = null;
	
	public GsonExt(){
		gson = new Gson();
	}
	
	public String toJson(Object src){
		try {
			return gson.toJson(src);
		} catch (Exception e) {
			logger.error("fail to json:"+src);
			return null;
		}
	}
	
	public <Object> Object fromJson(String json, Class<Object> classOfT){
		
		if(json==null || "".equals(json.trim())){
			return null;
		}
		try {
			return gson.fromJson(json, classOfT);
		} catch (JsonSyntaxException e) {
			logger.error("fail to parse json data:"+json);
			return null;
		}
	}
	
	public <Object> Object fromJson(String json, Type typeOfT){
		
		if(json==null || "".equals(json.trim())){
			return null;
		}
		try {
			return gson.fromJson(json, typeOfT);
		} catch (JsonSyntaxException e) {
			logger.error("fail to parse json data:"+json);
			return null;
		}
	}
	
	
}
